package com.px.auth.security;

import com.google.common.collect.ImmutableMap;
import com.px.auth.config.ApiSecurityConfig;
import com.px.auth.mapper.UserMapper;
import com.px.auth.model.UserModel;
import com.px.common.core.Response;
import com.px.common.util.FastUtil;
import com.px.common.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.MacSigner;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class AjaxAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void onAuthenticationSuccess(
            HttpServletRequest request,
            HttpServletResponse response,
            Authentication authentication) throws IOException {
        long iat = System.currentTimeMillis() / 1000;
        String claims = JsonUtil.toJson(new HashMap<String, String>() {{
            put("iss", "video");
            put("iat", String.valueOf(iat));
            put("exp", String.valueOf(iat + ApiSecurityConfig.EXPIRE_SECONDS));
            put("userid", authentication.getName());
            put("roles", authentication.getAuthorities()
                    .stream().map(Object::toString).collect(Collectors.joining(",")));
        }});

        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        if (claims == null){
            response.getWriter().println(JsonUtil.toJson(Response.success(null)));
        }else{
            Map<String, String> headers =
                    ImmutableMap.<String, String>builder().build();
            String jwtEcd = JwtHelper.encode(
                    claims, new MacSigner(ApiSecurityConfig.JWT_SIGNER_STR), headers).getEncoded();
            response.getWriter().println(JsonUtil.toJson(Response.success(jwtEcd)));
        }
        response.getWriter().flush();

        userMapper.updateIp(UserModel.builder()
                .id(Long.valueOf(authentication.getName())).ip(FastUtil.getClientIP(request)).build());

        clearAuthenticationAttributes(request);
    }
}
